﻿using System;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;

namespace MVCMS.Util.Persistence
{
    /// <summary>
    /// Wrapper for setting up an object db using db4o
    /// </summary>
    class Db4oManager
    {
        static readonly object padlock = new object();
        public static IObjectServer Server { get; private set; }
        public static IObjectContainer Client { get; private set; }

        static Db4oManager()
        {
            DBPath = "./db.db4o";
            Server = Db4oFactory.OpenServer(config, DBPath, 0);
            Client = Server.OpenClient(config);
        }

        public static string DBPath { get; private set; }
        private static IConfiguration config = Db4oFactory.NewConfiguration();
        public static void WithContainer(Action<IObjectContainer> action)
        {
            IObjectServer server = Db4oFactory.OpenServer(config, DBPath, 0);
            try
            {
                using (var container = server.OpenClient())
                {
                    action(Client);
                }
            }
            finally
            {
                server.Close();
            }
        }
    }
}